using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace FactoryAutoMatic.Dao
{
  class ConfigIni
  {
    /// <summary>
    /// 为INI文件中指定的节点取得字符串
    /// </summary>
    /// <param name="section">欲在其中查找关键字的节点名称</param>
    /// <param name="key">欲获取的项名</param>
    /// <param name="val">指定的项没有找到时返回的默认值</param>
    /// <param name="filePath">INI文件完整路径</param>
    [DllImport("kernel32")]
    private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
    /// <summary>
    /// 为INI文件中指定的节点取得字符串
    /// </summary>
    /// <param name="section">欲在其中查找关键字的节点名称</param>
    /// <param name="key">欲获取的项名</param>
    /// <param name="val">指定的项没有找到时返回的默认值</param>
    /// <param name="def">指定一个字串缓冲区，长度至少为nSize</param>
    /// <param name="retVal">指定装载到lpReturnedString缓冲区的最大字符数量</param>
    /// <param name="filePath">INI文件完整路径</param>
    /// <returns>复制到lpReturnedString缓冲区的字节数量，其中不包括那些NULL中止字符</returns>
    [DllImport("kernel32")]
    private static extern long GetPrivateProfileString(string section, string key, string def, System.Text.StringBuilder retVal, int size, string filePath);

    /// <summary>
    /// 写INI文件值 INIWrite()
    /// </summary>
    /// <param name="section">欲在其中写入的节点名称</param>
    /// <param name="key">欲设置的项名</param>
    /// <param name="val">要写入的新字符串</param>
    /// <param name="path">INI文件完整路径</param>
    /// <returns>非零表示成功，零表示失败</returns>
    public void INIWrite(string section, string key, string val, string path)
    {
      WritePrivateProfileString(section, key, val, path);
    }

    /// <summary>
    /// 读取INI文件值 INIRead()
    /// </summary>
    /// <param name="section">节点名</param>
    /// <param name="key">键</param>
    /// <param name="temp">未取到值时返回的默认值</param>
    /// <param name="path">INI文件完整路径</param>
    /// <returns>返回读取的值</returns>
    public string INIRead(string section, string key, string path)
    {
      //每次从ini中读取多少字节
      System.Text.StringBuilder temp = new System.Text.StringBuilder(1024);
      //section = 配置节点 key=键名 path=路径
      GetPrivateProfileString(section, key, "", temp, 1024, path);
      return temp.ToString();
    }
  }
}
